package com.example.myaku;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.activity.OnBackPressedCallback;

public class ListFragment extends Fragment {

    private WebView webView;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);

        webView = view.findViewById(R.id.xiaozhi_web_view);

        if (webView != null) {
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setDatabaseEnabled(true);
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
            webSettings.setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36");

            webView.setWebViewClient(new WebViewClient());
            webView.loadUrl("https://xiaozhi.me/");
        } else {
            Log.e("ListFragment", "WebView is null. Check layout or ID.");
        }

        // 注册返回键监听器
        requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (webView != null && webView.canGoBack()) {
                    webView.goBack(); // WebView 返回上一页
                } else {
                    // 如果 WebView 已经是首页，才允许 Fragment 出栈或 Activity finish
                    setEnabled(false); // 临时禁用回调，防止重复触发
                    requireActivity().onBackPressed(); // 调用默认返回逻辑
                }
            }
        });

        return view;
    }
}
